package com.lecyon.farm.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.lecyon.farm.common.enums.ExcelFileEnum;
import com.lecyon.farm.service.IExcelService;
import com.lecyon.farm.service.IQiniuService;
import com.lecyon.farm.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Excel操作相关 服务实现类
 *
 * @author Yao Zheng
 * @Date 2019/10/18 11:05
 */
@Service
@Slf4j
public class ExcelServiceImpl implements IExcelService {

    private IQiniuService qiniuService;

    /**
     * 自定义导出excel
     *
     * @param list          要导出的结果
     * @param excelFileEnum 导出要素
     * @return
     */
    @Override
    public String exportExcel(List<?> list, @NotNull ExcelFileEnum excelFileEnum) throws IOException {
        String downLoadUrl;
        String fileName = FileUtils.generatorGapExportExcelFileName(excelFileEnum.getFileName());
        ExportParams exportParams = new ExportParams(excelFileEnum.getTitleName(), excelFileEnum.getSheetName(), ExcelType.XSSF);
        downLoadUrl = farmExport(exportParams, excelFileEnum.getPojoClass(), list, fileName);
        return downLoadUrl;
    }

    /**
     * Farm平台的excel导出
     *
     * @param list
     * @param fileName
     * @param exportParams
     * @return
     */
    private String farmExport(ExportParams exportParams, Class<?> pojoClass, List<?> list, String fileName) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        String downLoadUrl = upLoadExcel(fileName, workbook);
        return downLoadUrl;
    }

    /**
     * 上传到七牛
     *
     * @param fileName 文件名
     * @param workbook 生成的Workbook对象
     * @return 文件下载地址
     * @throws IOException
     */
    private String upLoadExcel(String fileName, Workbook workbook) throws IOException {
        InputStream inputStream;
        String downloadUrl;
        inputStream = FileUtils.workbookToInputStream(workbook);
        downloadUrl = qiniuService.uploadFileToQiniu(fileName, inputStream);
        return downloadUrl;
    }

    /**
     * ----------------------------- 分割线 以下是setter方法，用于替换field上的@Autowired -----------------------------
     **/

    @Autowired
    @Lazy
    public void setQiniuService(IQiniuService qiniuService) {
        this.qiniuService = qiniuService;
    }
}
